from django.contrib import admin
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import path
import logging
from urllib.parse import urlencode, quote_plus, unquote
import requests

# 假设这些枚举和模型在你的项目中已经定义
# 如果没有，需要创建它们
from enum import Enum

class PlatformTypeEnum(Enum):
    AMAZON = "amazon"

    @classmethod
    def getType(cls):
        return cls.AMAZON.value

# 模拟配置获取服务
class ApiSettingFeign:
    def getDetailByServiceCode(self, service_code):
        # 实际应该从数据库或配置文件获取
        # 这里返回模拟数据
        return {
            "data": {
                "paramMap": {
                    "redirect_url": "https://your-redirect-url.com/callback",
                    "token_url": "https://api.amazon.com/token",
                    "client_id": "your-client-id",
                    "client_secret": "your-client-secret"
                }
            }
        }

# 平台账号授权服务
class PfCustomerAuthService:
    def getByPlatformCodeAndAccount(self, platform_code, account_id):
        # 实际应该从数据库获取账号信息
        # 这里返回模拟数据
        return {
            "platform_account_id": 12345,
            "selling_partner_id": account_id,
            "platform_code": platform_code
        }

    def updateTokenById(self, account_id, access_token, refresh_token, expires_in):
        # 实际应该更新数据库中的Token信息
        logging.info(f"Updating token for account {account_id}")
        return True

# 亚马逊服务类
class AmazonService_pa:
    def __init__(self):
        self.apiSettingFeign = ApiSettingFeign()
        self.pfCustomerAuthService = PfCustomerAuthService()
    def generateRedirectUrl(self, amazonCallbackUri, amazonState):
        """生成亚马逊授权重定向URL"""
        lgApiSettingDto = self.apiSettingFeign.getDetailByServiceCode(PlatformTypeEnum.AMAZON.getType()).get('data')
        if not lgApiSettingDto:
            raise ValueError("AMAZON未配置平台api信息")      
        paramMap = lgApiSettingDto.get('paramMap', {})
        redirectPath = paramMap.get("redirect_url")        
        return f"{amazonCallbackUri}?redirect_uri={redirectPath}&state={amazonState}"

    def handlerCodeBack(self, sellingPartnerId, spapiOauthCode):
        """处理授权回调，获取并更新Token"""
        # 获取平台账号
        pfCustomerAuth = self.pfCustomerAuthService.getByPlatformCodeAndAccount(
            PlatformTypeEnum.AMAZON.getType(), 
            sellingPartnerId
        )
        
        # 获取配置
        lgApiSettingDto = self.apiSettingFeign.getDetailByServiceCode(
            PlatformTypeEnum.AMAZON.getType()
        ).get('data')
        
        if not lgApiSettingDto:
            logging.error(f"amazon账号授权失败，未配置平台api信息，sellingPartnerId: {sellingPartnerId}")
            raise ValueError("privilege grant failed")
        
        apiParamMap = lgApiSettingDto.get('paramMap', {})
        
        # 获取token
        try:
            tokenVO = self.getToken(apiParamMap, spapiOauthCode)
        except Exception as e:
            logging.error(f"亚马逊授权获取Token失败: {str(e)}")
            raise ValueError("privilege grant failed")
        
        if not tokenVO or not tokenVO.get('access_token'):
            raise ValueError("invalid_grant")
        
        # 更新平台账号token信息
        self.pfCustomerAuthService.updateTokenById(
            pfCustomerAuth.get('platform_account_id'),
            tokenVO.get('access_token'),
            tokenVO.get('refresh_token'),
            tokenVO.get('expires_in')
        )
        
        return apiParamMap

    def getToken(self, apiParamMap, spapiOauthCode):
        
        url = apiParamMap.get('token_url')
        data = {
            'grant_type': 'authorization_code',
            'code': spapiOauthCode,
            'client_id': apiParamMap.get('client_id'),
            'client_secret': apiParamMap.get('client_secret')
        }
        
        response = requests.post(url, data=data)
        
        if response.status_code == 200:
            return response.json()
        else:
            logging.error(f"获取Token失败: {response.text}")
            raise Exception(f"获取Token失败: {response.status_code}")

# 自定义管理视图
class AmazonAdmin(admin.ModelAdmin):
    amazon_service = AmazonService_pa()
    def get_urls(self):
        """添加自定义URL路由"""
        custom_urls = [
            path('amazon/codeback/', self.admin_site.admin_view(self.amazon_codeback_view), name='amazon_codeback'),
            path('amazon/authorize/', self.admin_site.admin_view(self.amazon_authorize_view), name='amazon_authorize'),
        ]
        return custom_urls + super().get_urls()

    def amazon_authorize_view(self, request):
        """处理亚马逊授权请求，生成并跳转至授权URL"""
        selling_partner_id = request.GET.get('selling_partner_id')
        amazon_callback_uri = request.GET.get('amazon_callback_uri', 'https://sellercentral.amazon.com/apps/authorize/consent')
        amazon_state = request.GET.get('amazon_state', f'state_{selling_partner_id}')
        
        if not selling_partner_id:
            return HttpResponse("Missing selling_partner_id parameter", status=400)
        
        try:
            redirect_url = self.amazon_service.generateRedirectUrl(amazon_callback_uri, amazon_state)
            return HttpResponseRedirect(unquote(redirect_url))
        except Exception as e:
            logging.error(f"生成亚马逊授权URL失败: {str(e)}")
            return HttpResponse(f"授权失败: {str(e)}", status=500)

    def amazon_codeback_view(self, request):
        """处理亚马逊授权回调"""
        selling_partner_id = request.GET.get('selling_partner_id')
        spapi_oauth_code = request.GET.get('spapi_oauth_code')
        error = request.GET.get('error')
        
        if error:
            logging.error(f"亚马逊授权错误: {error}, selling_partner_id: {selling_partner_id}")
            return HttpResponse(f"授权错误: {error}", status=400)
        
        if not spapi_oauth_code:
            return HttpResponse("Missing spapi_oauth_code parameter", status=400)
        
        try:
            api_param_map = self.amazon_service.handlerCodeBack(selling_partner_id, spapi_oauth_code)
            return HttpResponse("授权成功！")
        except ValueError as e:
            logging.error(f"亚马逊授权处理失败: {str(e)}")
            return HttpResponse(f"处理失败: {str(e)}", status=400)
        except Exception as e:
            logging.error(f"亚马逊授权处理异常: {str(e)}")
            return HttpResponse(f"系统异常: {str(e)}", status=500)

# 注册模型与管理类（如果有相关模型）
# 假设你的模型名为AmazonAuthorization
# from .models import AmazonAuthorization
# admin.site.register(AmazonAuthorization, AmazonAdmin)